/**
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Company: ---Technology Co. Ltd</p>
 * <p>2014-4-29</p>
 * @author Jan.Zhang
 */
package com.xianl.busiplat.mybatis;

import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


/** 
 * desc:Mybatis Session create Factory
 * <p>author: Jan.Zhang </p>
 * date: 2014-4-29
 */
public class SessionFactory {

//	private final static Logger logger = LoggerFactory.getLogger(SessionFactory.class);
	private final static String RESOURCE = "mybatis/Configuration.xml";
	private static SqlSessionFactory sqlSessionFactory = null;
	private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();

	public static SqlSessionFactory getSqlSessionFactory() {
		return sqlSessionFactory;
	}

	static {
		Reader reader = null;
		try {
			reader = Resources.getResourceAsReader(RESOURCE);
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		} catch (IOException e) {
//			logger.error("Get Mybatis Resouce Error ", e);
			throw new RuntimeException("Get Mybatis Resouce Error " + RESOURCE, e);
		}
	}

	public static SqlSession getSession() {
		SqlSession sqlSession = threadLocal.get();
		if(sqlSession == null ) {
			if(sqlSessionFactory == null ) {
				getSqlSessionFactory();
			}
			sqlSession = sqlSessionFactory == null ? null : sqlSessionFactory.openSession();
		}
		return sqlSession;
	}

	public void closeSqlSession() {
		SqlSession sqlSession = threadLocal.get();
		threadLocal.set(null);
		if(sqlSession != null ) {
			sqlSession.close();
//			logger.debug("Close SqlSession Success");
		}
//		logger.debug("SqlSession is Null");
	}
}
